<?php
class Admin_UserGroupController extends Apps_Controller_Action {

	// Default user_group_id
	const DEFAULT_USER_GROUP_ID = 1;

	public function indexAction() {
		$this->_forward('read');
	}

	public function readAction() {
		$this->actResolve('act_delete',
						  'delete', 'user-group', 'admin', array('id' => $this->_getParam('item_checker')),
						  true);

		$q = $this->_dbAdapter
				  ->select()
				  ->from('user_group')
				  ->where('user_group.id != ?', self::DEFAULT_USER_GROUP_ID);

		$grid = new Grid_User_UserGroup('user-group-grid');
		$grid->setSource(new OeZend_Widget_Grid_Source_ZendDbSelect($q))
		     ->setCaption('Group User List')
		     ->setDisableCheckbox()
		     ->setDisablePaginator()
		     ->setView(new OeZend_Widget_Grid_View())
		     ->deploy();

		$this->view->grid = $grid;
	}

	public function createAction() {
	    $rq   = $this->_request;
        if($rq->isPost()) {
	        $data['title']  	 = $rq->getParam('group-title');
	        $data['name']  		 = $rq->getParam('group-name');

	        if(!$data['title'] ||  !$data['name']) {
	            $this->_flashMessenger->addMessage('Tên hoặc chức vụ nhóm chưa nhập, vui lòng nhập vào.');
	            $this->goBack();
	        }

			$data['description'] = $rq->getParam('description');
	        $roles 		 		 = $rq->getParam('roles');

	        $tbUserGroup = new Model_DbTable_UserGroup();
	        $tbGroupAction = new Model_DbTable_GroupAction();

	        //ADD User Group
	        $r = $tbUserGroup->safelyInsert($data);
	        //ADD Role
	        if($r) {
				$this->addGroup($roles, $r);
				$this->_flashMessenger->addMessage(self::$msgAddSuccess);
				$this->_redirect('/admin/user-group/read');
	        }
        	$this->goToActionIndex();
        }
	}


	public function updateAction() {
		$rq            = $this->_request;
		$tbUserGroup   = new Model_DbTable_UserGroup();
		$tbGroupAction = new Model_DbTable_GroupAction();
		$tbUser 	   = new Model_DbTable_User();

		// Get data show in Form
		$userGroupId   = $rq->getParam('id');

		if(!$userGroupId || !($dataGroup = $tbUserGroup->fetchRow(array('id = ?' => $userGroupId))->toArray())) {
			$this->_flashMessenger->addMessage(self::$msgNoRecordFound);
			return $this->_redirect('/admin/user-group/read');
		}

		// Group_Default cannot edit
			if($userGroupId == self::DEFAULT_USER_GROUP_ID) {
				$this->_flashMessenger->addMessage('Nhóm người dùng mặc định không được thay đổi');
				return $this->goToActionIndex();
			}

		// Get Roles  to show in checkbox
			$privilege = $tbGroupAction->getListActionFromGroupAction($userGroupId);
		$rolesGroup = $this->getRolesGroup($privilege);
		$this->view->data  = $dataGroup;
		$this->view->roles = $rolesGroup;

		// Create new Group and Delete old Group
		if($rq->isPost()) {
			$oldGroupId 		 = $rq->getParam('id');
			$data['title']  	 = $rq->getParam('group-title');
			$data['name']  		 = $rq->getParam('group-name');
			$data['description'] = $rq->getParam('description');
			$roles 		 		 = $rq->getParam('roles');
	//ADD User Group
	        $r = $tbUserGroup->safelyInsert($data);
	        //ADD Role
	        if($r) {
		        $this->addGroup($roles, $r);

		        // Delete old Group
				$tbUser->safelyUpdate(array('user_group_id' => $r), array('user_group_id = ?' => $oldGroupId));

				$tbUserGroup->safelyDelete(array('id = ?' => $oldGroupId));
				$this->_flashMessenger->addMessage(self::$msgUpdateSuccess);
				$this->_redirect('/admin/user-group/read');
			}
		}

	}

	public function deleteAction() {
		$this->disableLayout(true, true);
		$rq = $this->_request;
		$groupIds = $rq->getParam('id');

		if(!$groupIds) {$this->goToActionIndex();}

		$tbUserGroup   = new Model_DbTable_UserGroup();
		$tbGroupAction = new Model_DbTable_GroupAction();
		if(is_array($groupIds)) {
			foreach ($groupIds as $groupId) {

				// Group_Default cannot delete
					if($groupId == self::DEFAULT_USER_GROUP_ID) {
						$this->_flashMessenger->addMessage('Nhóm Người dùng quản trị. Không được xóa');
						$this->_redirect('/admin/user-group/read');
					}

				$tbGroupAction->safelyDelete(array('user_group_id = ?' => $groupId));
				$tbUserGroup->safelyDelete(array('id = ?' => $groupId));
			}
			$this->_redirect('/admin/user-group/read');
		} elseif (is_numeric($groupIds)) {

			// Group_Default cannot delete
				if($groupIds == self::DEFAULT_USER_GROUP_ID) {
					$this->_flashMessenger->addMessage('Nhóm Người dùng quản trị. Không được xóa');
					$this->_redirect('/admin/user-group/read');
				}

			$tbGroupAction->safelyDelete(array('user_group_id = ?' => $groupIds));
			$r = $tbUserGroup->safelyDelete(array('id = ?' => $groupIds));
			$this->_flashMessenger->addMessage($r ? self::$msgDeleteSuccess : self::$msgDeleteError);
			$this->_redirect('/admin/user-group/read');
		} else {
			$this->_redirect('/admin/user-group/read');
		}
	}

	public function addGroup($roles, $r) {
		$tbGroupAction = new Model_DbTable_GroupAction();
    	// Default Access
    		$actionIds = $tbGroupAction->getActionByModule('default');
    		foreach ($actionIds as $k => $v) {
    			$d['user_group_id'] = $r;
    			$d['acl_action_id'] = $v['id'];
    			$tbGroupAction->safelyInsert($d);
    		}

    		$actionIds = $tbGroupAction->getActionByModule('a');
    		foreach ($actionIds as $k => $v) {
    			$d['user_group_id'] = $r;
    			$d['acl_action_id'] = $v['id'];
    			$tbGroupAction->safelyInsert($d);
    		}

			// access module Admin
    		$actionIds = $tbGroupAction->getArrayAction('admin', 'index');
    		foreach ($actionIds as $k => $v) {
    			$d['user_group_id'] = $r;
    			$d['acl_action_id'] = $v['id'];
    			$tbGroupAction->safelyInsert($d);
    		}

    		// Login logout
    		$actionIds = $tbGroupAction->getArrayAction('admin', 'auth');
    		foreach ($actionIds as $k => $v) {
    			$d['user_group_id'] = $r;
    			$d['acl_action_id'] = $v['id'];
    			$tbGroupAction->safelyInsert($d);
    		}

// Set Privilige
		foreach ($roles as $value) {
			//if($value != 'gallery') {
				$actionIds = $tbGroupAction->getArrayAction('admin', $value);
	        	foreach ($actionIds as $k => $v) {
		        	$d['user_group_id'] = $r;
					$d['acl_action_id'] = $v['id'];
		        	$tbGroupAction->safelyInsert($d);
	        	}

	        	// Photo management
// 	        	if($value == 'product') {
// 	        		$actionPhoto = $tbGroupAction->getAction('admin', 'image', $value);
// 					$d['user_group_id'] = $r;
// 					$d['acl_action_id'] = $actionPhoto['id'];
// 					$tbGroupAction->safelyInsert($d);
// 	        	}
// 			} else {
// 				$actionGalery = $tbGroupAction->getAction('admin', 'photo-management', $value);
// 				$d['user_group_id'] = $r;
// 				$d['acl_action_id'] = $actionGalery['id'];
// 				$a = $tbGroupAction->safelyInsert($d);
// 			}
        }
	}

	public function getRolesGroup($privilege) {
		$rolesGroup = array();
		foreach ($privilege as $value) {
			if($value['module_name'] == 'admin') {
				switch ($value['controller_name']) {
					case 'product' :
						$rolesGroup[] = 'product';
					    break;
					case 'product-category' :
						$rolesGroup[] = 'product-category';
					    break;
					case 'product-image' :
						$rolesGroup[] = 'product-image';
					    break;
					case 'product-status' :
						$rolesGroup[] = 'product-status';
					    break;
					case 'product-color' :
						$rolesGroup[] = 'product-color';
					    break;
					case 'product-size' :
						$rolesGroup[] = 'product-size';
					    break;
					case 'customer' :
						$rolesGroup[] = 'customer';
					    break;
					case 'order' :
						$rolesGroup[] = 'order';
					    break;
					case 'order-status' :
						$rolesGroup[] = 'order-status';
					    break;
					case 'payment-type' :
						$rolesGroup[] = 'payment-type';
					    break;
					case 'enquire' :
						$rolesGroup[] = 'enquire';
					    break;
					case 'contact' :
						$rolesGroup[] = 'contact';
					    break;
					case 'event' :
						$rolesGroup[] = 'event';
					    break;
					case 'faqs' :
						$rolesGroup[] = 'faqs';
					    break;
					case 'faqs-category' :
						$rolesGroup[] = 'faqs-category';
					    break;
					case 'article' :
						$rolesGroup[] = 'article';
					    break;
					case 'site-info' :
						$rolesGroup[] = 'site-info';
					    break;
					case 'site-setting' :
						$rolesGroup[] = 'site-setting';
					    break;
					case 'gallery' :
						$rolesGroup[] = 'gallery';
					    break;
					case 'support' :
						$rolesGroup[] = 'support';
					    break;
					case 'user' :
						$rolesGroup[] = 'user';
					    break;
					case 'user-group' :
						$rolesGroup[] = 'user-group';
					    break;
					case 'ckfinder' :
						$rolesGroup[] = 'ckfinder';
					    break;
				}
			}
		}
			// Filter array : Only use for this $roleGroup()
			$result = array();
			$temp = '';
			for($i = 0; $i < count($rolesGroup); $i++) {
				if($rolesGroup[$i] != $temp) {
					$result[] = $rolesGroup[$i];
					$temp = $rolesGroup[$i];
				}
			}

		return $result;
	}
}
